
from coffeetalk.protocol import ioml, requests
from coffeetalk.utilities import objectmaker

SYSTEMSTREAMS = """
<ioml version="1.0">
<h />
<b>
    <i n="System">
        <i n="Config">
            <i n="Logging" />
            <i n="Servers" />
        </i>
        <i n="Network">
            <i n="Clients">
                <i n="Connecting" />
                <i n="Users">
                    <i n="Login" />
                    <i n="Disconnect" type="[Stream]" />
                    <i n="Connected" />
                </i>
                <i n="System">
                    <i n="Login" />
                    <i n="Disconnect" type="[Stream]" />
                    <i n="Connected" />
                </i>
            </i>
        </i>
    </i>
</b>
</ioml>
"""
class StartupConfig(object):
    
    def __init__(self,configstring='',configpath=None,ioclient=None):
        
        self.configstring = configstring
        self.ioclient = ioclient
        
        self.ioml = None
        self.config = None
        
        if configpath is not None:
            self.ioml = ioml.IOML(filepath=configpath)
        elif self.configstring != '':
            self.ioml = ioml.IOML(iomlstring=self.configstring)
        
        self.config = objectmaker.ObjectMaker().make_object(self.ioml.bodyelement)
        self.load_loggers()
        self.load_network_config()
        
    def load_loggers(self):
        
        if self.config is None: return
        
        self.ioclient.add(requests.Add(path='/System/Config/Logging/',iobject=self.config.StandardLogging,on_error=self.handle_error))
        self.ioclient.add(requests.Add(path='/System/Config/Logging/',iobject=self.config.FileLogging,on_error=self.handle_error))
    
    def load_network_config(self):
        
        if self.config is None: return
        
        self.ioclient.add(requests.Add(path='/System/Config/Servers/',iobject=self.config.Network,on_error=self.handle_error))
                            
    def handle_error(self,env,path,request,reason):
        print 'Env: %s\nPath: %s\nRequest: %s\nReason: %s' % (str(env),path,str(request),reason)
    
def load_config(**kwargs):

    for k,v in kwargs.iteritems():
        print '%s:%r' % (k,v)
    
    return
    i = ioml.IOML(filepath='iotpd.conf')
    #print i
    
    om = objectmaker.ObjectMaker()
    
    obj = om.make_object(i.bodyelement)
    
    #print obj
    
    for key,value in obj.iteritems():
        print '%s:%r' % (key,value)
    
if __name__ == '__main__':
    #load_config(**{'a':1,'b':2})
    conf = StartupConfig()
    conf.load_config('default_iotpd.conf')
    print type(conf.config)
    print conf.config
    
    
    